package com.winner.data.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring Context 工具类  可以方便地引用各种 bean而不需要注入，通常用它来获取延时加载的 bean 信息。
 * 获取应用上下文通用类(以静态变量保存SpringApplicationContext,可在任何代码任何地方任何时候中取出ApplicaitonContext)
 *
 * 使用Spring Boot时，通过依赖注入获取bean是非常方便的,但是在工具化的应用场景下，想要动态获取bean就变得非常困难.
 * 于是Hutool封装了Spring中Bean获取的工具类——SpringUtil。
 * UserService bean = SpringUtil.getBean(UserService.class); UserService bean = SpringUtil.getBean("userService"); 推荐hutool
 * UserService bean = SpringContextUtil.getBean(UserService.class); 不那么推荐
 *
 * @author wangxinle5
 * @since 2023-01-03
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}
	public static <T> T getBean(Class<T> clazz){
		return applicationContext.getBean(clazz);
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}

	public static Class<?> getType(String name) {
		return applicationContext.getType(name);
	}

}
